//
//  CreateDiscussViewController.m
//  OperationPro
//
//  Created by yaxue wang on 16/10/9.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "CreateDiscussViewController.h"
#import "BankView.h"
#import "CQiniuFileUpload.h"
#import "QNUploadOption.h"
#import "CFileUpload.h"
#import "UIImage+ResizeMagick.h"
#import "DiscussDetailViewController.h"
#import "CTextField.h"
#define _UIKeyboardFrameEndUserInfoKey (&UIKeyboardFrameEndUserInfoKey != NULL ? UIKeyboardFrameEndUserInfoKey : @"UIKeyboardBoundsUserInfoKey")
@interface CreateDiscussViewController ()<UITextViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    TPKeyboardAvoidingScrollView *_scrollView;
    BankView *_bgView;
   
    BOOL isNewImg;
    UIImage *_newIamge;
}
@property (nonatomic, strong)UIPickerView *pickerView;
@property (nonatomic, strong)NSArray *dataAr;
@property (nonatomic, strong)  NSString *type;
@property (nonatomic, strong)  UILabel *typeLab;
@property (nonatomic, strong)  UITextView *titleTF;
@property (nonatomic, strong)  UITextView *detailTF;
@property (nonatomic, strong)  UIImageView *imgView;
@property (nonatomic, strong)  UIView *delView;
@property (nonatomic, strong)  UIImageView *delImg;


@end

@implementation CreateDiscussViewController
//- (void)viewDidAppear:(BOOL)animated
//{
//    [super viewDidAppear:animated];
//    [self setIsLoading:NO];
//
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"发布讨论贴"];
    self.hide=YES;
    __block typeof(self) blockself = self;

    [self.navBar setBackAction:^{
            if (([_titleTF.text isEqualToString:@""]||[_titleTF.text isEqualToString:@"讨论贴标题"])&&([_detailTF.text isEqualToString:@""]||[_detailTF.text isEqualToString:@"描述问题或分享经验..."])) {
                [blockself backController];
                
                
            }else
            {
                [CClass showAlertTitle:nil hidden:NO context:@"离开后内容丢失。是否离开？" oneBtn:@"离开" twoBtn:@"取消" handler:^{
                    [blockself backController];
 
                } handler:^{
                    
                }];
              
            }
            
        }];
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HideKeyboard2:) name:UIKeyboardWillHideNotification object:nil];
    [self.navBar createRightBtn:@"发送" block:^{
        
        if ([_typeLab.text isEqualToString:@""]) {
            [CClass showMessage:@"请选择类型"];
            return;
        }
        if ([_titleTF.text isEqualToString:@""]||[_titleTF.text isEqualToString:@"讨论贴标题"]) {
            [CClass showMessage:@"请输入标题！"];
            return;
        }
        if ([_detailTF.text isEqualToString:@""]||[_detailTF.text isEqualToString:@"描述问题或分享经验..."]) {
            [CClass showMessage:@"请输入详情！"];
            return;
        }
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        [dic setObject:_titleTF.text forKey:@"title"];
        [dic setObject:_detailTF.text forKey:@"content"];
        if ([_typeLab.text isEqualToString:@"提问"]) {
            [dic setObject:@"01" forKey:@"kind"];
            
        }else if ([_typeLab.text isEqualToString:@"讨论"]) {
            [dic setObject:@"02" forKey:@"kind"];
            
        }else if ([_typeLab.text isEqualToString:@"经验"]) {
            [dic setObject:@"03" forKey:@"kind"];
            
        }
        NSMutableArray *ar=[[NSMutableArray alloc]init];
        [self setIsLoading:YES];

        if (isNewImg==NO) {
            //默认图片
            [CClass HttpRequestTask:YES withUrl:@"discuss_create" withData:dic notifyError:YES onSuccess:^(BaseModel *model) {
                [CClass showMessage:@"发布成功" completion:^{
#pragma mark  贴子的详情
                    DiscussDetailViewController *disscussVC=[[DiscussDetailViewController alloc]init];

                    [CClass HttpRequestTask:YES withUrl:@"discuss_detail" withData:@{@"uuid":[model.B_data objectForKey:@"uuid"]} notifyError:YES onSuccess:^(BaseModel *model) {
                        disscussVC.invitationModel=[[InvitationModel alloc] initWithDictionary:model.B_data error:nil];
                        disscussVC.isWarnuiud=NO;

                        [self pushController:disscussVC Lever:1 Animated:YES];
                        [self setIsLoading:NO];

                    } onError:^(BaseModel *model) {
                        [self setIsLoading:NO];

                    }];
                    
                }];
            } onError:^(BaseModel *model) {
                [self setIsLoading:NO];

            }];
            
            
        }else
        {
            //新图片
            NSString *imgName = [NSString stringWithFormat:@"%@_%@.jpg", [Common getDateTimeString], [Common randomStringWithLength:8]];
            NSData *data =[_newIamge resizedAndReturnData];
            [ar addObject:[CFileModel initWithFile:data name:imgName]];
            [dic setObject:imgName forKey:@"image"];

            [[CQiniuFileUpload uploadFile] uploadFiles:ar progress:^(CFileUpload *upload, float per) {
                
            } finish:^(CFileUpload *upload, NSArray *models, NSError *error) {
                if (ar.count>0) {
                    
                    [CClass HttpRequestTask:YES withUrl:@"discuss_create" withData:dic notifyError:YES onSuccess:^(BaseModel *model) {
                        [CClass showMessage:@"发布成功" completion:^{
                         
#pragma mark  贴子的详情
                            DiscussDetailViewController *disscussVC=[[DiscussDetailViewController alloc]init];

                            [CClass HttpRequestTask:YES withUrl:@"discuss_detail" withData:@{@"uuid":[model.B_data objectForKey:@"uuid"]} notifyError:YES onSuccess:^(BaseModel *model) {
                                disscussVC.invitationModel=[[InvitationModel alloc] initWithDictionary:model.B_data error:nil];
                                disscussVC.isWarnuiud=NO;
                                [self pushController:disscussVC Lever:1 Animated:YES];

                            } onError:^(BaseModel *model) {
                                [self setIsLoading:NO];
 
                            }];
                        }];
                    } onError:^(BaseModel *model) {
                        [self setIsLoading:NO];
                    }];
                    
                }
            }];
            
            
        }
        
        
        
    }];
    _scrollView=[[TPKeyboardAvoidingScrollView alloc]initWithFrame:CGRectMake(0, 64, WindowWidth, WindowHeight-64)];
    _scrollView.contentSize=CGSizeMake(WindowWidth, WindowHeight+100);
    [self.view addSubview:_scrollView];
    //    _scrollView.scrollEnabled=NO;
    _scrollView.backgroundColor =[UIColor whiteColor];
    [_scrollView addSubview:self.typeLab];
    [_scrollView addSubview:self.titleTF];
    [_scrollView addSubview:self.detailTF];
    [_scrollView addSubview:self.imgView];
    [_scrollView addSubview:_delView];

    _bgView =[[BankView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, WindowHeight)witnOriginY:WindowHeight/3 withTitle:@"分类"];
    _bgView.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.4];
    [self.view bringSubviewToFront:_bgView];
    [self.view addSubview:_bgView];
    _bgView.hidden=YES;
    _pickerView=[[UIPickerView alloc]initWithFrame:CGRectMake(0, 40, WindowWidth, WindowHeight/3-40)];
    _pickerView.delegate=self;
    _pickerView.dataSource=self;
    _pickerView.backgroundColor =[UIColor whiteColor];
    _pickerView.showsSelectionIndicator=YES;
    [_bgView.whiteView addSubview:_pickerView];
    _dataAr=[[NSArray alloc]initWithObjects:@"提问",@"经验",@"讨论", nil];
    [_pickerView reloadAllComponents];
    [_bgView setSubmitBtnPress:^{
        int component0= [blockself.pickerView selectedRowInComponent:0];
        blockself.type=[blockself.dataAr objectAtIndex:component0];
        blockself.typeLab.text=blockself.type;
        
    }];
    NSArray *ar=[[NSArray alloc]initWithObjects:@"分类",@"标题",@"详情",@"图片", nil];
    
    for (int i=0; i<4; i++) {
        
        UILabel *nameLab = [[UILabel alloc]init];
        [_scrollView addSubview:nameLab];
        nameLab.textColor =FontColor;
        nameLab.font =F(15);
        nameLab.text=[ar objectAtIndex:i];
        UILabel *line =[[UILabel alloc]init];
        line.backgroundColor = LineColor;
        [_scrollView addSubview:line];
        if (i==0) {
            UIImage *image = [UIImage imageNamed:@"Ico_discuss_next"];
            UIImageView *nextImgeView = [[UIImageView alloc] initWithFrame:CGRectMake(WindowWidth-15-image.size.width, (50-image.size.height)/2, image.size.width, image.size.height)];
            nextImgeView.image=image;
            [_scrollView addSubview:nextImgeView];
            nameLab.frame=CGRectMake(15, 0, 70, 50);
            line.frame=CGRectMake(15,(50-0.5), WindowWidth, 0.5);
        }else if (i==1)
        {
            nameLab.frame=CGRectMake(15, 50*i, 80, 50);
            line.frame=CGRectMake(15,(50-0.5)+50*i, WindowWidth, 0.5);
        }
        else if (i==2)
        {
            nameLab.frame=CGRectMake(15, 50*i, 80, 100);
            line.frame=CGRectMake(15,(100-0.5)+50*i , WindowWidth, 0.5);
        }else if (i==3)
        {
            nameLab.frame=CGRectMake(15, 50*2+100, 80, 70);
            line.frame=CGRectMake(15,(70-0.5)+50*2+100 , WindowWidth, 0.5);
        }
        
    }
    
    
}
- (void) HideKeyboard2:(NSNotification*)notification{
    
    _scrollView.contentOffset=CGPointMake(0, 0);
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    
}
- (UILabel *)typeLab{
    if (_typeLab == nil) {
        UIImage *image = [UIImage imageNamed:@"Ico_discuss_next"];
        _typeLab = [[UILabel alloc] initWithFrame:CGRectMake(WindowWidth/2-15-image.size.width, 0, WindowWidth/2-image.size.width-10, 50)];
        _typeLab.text=@"提问";
        _typeLab.userInteractionEnabled=YES;
        _typeLab.textAlignment =NSTextAlignmentRight;
        _typeLab.textColor=MainColor;
        [_typeLab setFont:F(15)];
        [_typeLab bk_whenTapped:^{
            _bgView.hidden=NO;
            int i = 0;
            for (int j=0;j<_dataAr.count;j++) {
                if ([[_dataAr objectAtIndex:j] isEqualToString:self.typeLab.text]) {
                    [_pickerView selectRow:j inComponent:0 animated:YES];
                    break;
                }
                i ++;
            }
            if (i == _dataAr.count) {
                self.type=[_dataAr objectAtIndex:0];
            }
            
            [UIView animateWithDuration:0.5 animations:^{
                _bgView.whiteView.frame=CGRectMake(0,WindowHeight/3*2 , WindowWidth, WindowHeight/3);
            } completion:nil];
        }];
    }
    return _typeLab;
}

- (UITextView *)titleTF{
    if (_titleTF == nil) {
        _titleTF = [[UITextView alloc] initWithFrame:CGRectMake(WindowWidth/2-15, 50, WindowWidth/2, 50)];
        _titleTF.textAlignment =NSTextAlignmentRight;
        [_titleTF setText:@"讨论贴标题"];
        _titleTF.delegate=self;
        [_titleTF setTextColor:C(@"cbcbcb")];
        [_titleTF setFont:F(12)];
    }
    return _titleTF;
}
- (UITextView *)detailTF{
    if (_detailTF == nil) {
        _detailTF = [[UITextView alloc] initWithFrame:CGRectMake(WindowWidth/2-15,50*2+10, WindowWidth/2, 80)];
        _detailTF.textAlignment =NSTextAlignmentRight;
        [_detailTF setText:@"描述问题或分享经验..."];
        [_detailTF setTextColor:C(@"cbcbcb")];
        _detailTF.delegate=self;
        [_detailTF setFont:F(12)];
    }
    return _detailTF;
}

- (UIImageView *)imgView{
    if (_imgView == nil) {
        UIImage *img = [UIImage imageNamed:@"Ico_Upload_ImageDefault"];
        _imgView = [[UIImageView alloc] initWithFrame:CGRectMake(WindowWidth-img.size.width-15, 50*2+100+(70-img.size.height)/2, img.size.width, img.size.height)];
        [_imgView setImage:img];
        _imgView.userInteractionEnabled=YES;
        [_imgView bk_whenTapped:^{
            if (isNewImg == NO) {
                [self chooseClick];
                
            }else
            {
                [XWScanImage scanBigImageWithImageView:_imgView];

            }
        }];
        [_imgView.layer setMasksToBounds:YES];
        UIImage *imgdel = [UIImage imageNamed:@"photo_delete"];
        _delView = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_imgView.frame) - 30, CGRectGetMinY(_imgView.frame), 30, 30)];
        [_delView bk_whenTapped:^{
            [_imgView setImage:img];
            _newIamge = nil;
            isNewImg = NO;
            _delView.hidden=YES;
        }];
        _delImg=[[UIImageView alloc]initWithFrame:CGRectMake(15, 0, 15, 15)];
        [_delView addSubview:_delImg];
        _delImg.userInteractionEnabled=YES;
        _delImg.image=imgdel;
        [_delView setHidden:YES];

    }
    return _imgView;
}
#pragma mark 输入框的限制

- (void)textViewDidBeginEditing:(UITextView *)textView{
    if(textView==_detailTF)
    {
        if ([textView.text isEqualToString:@"描述问题或分享经验..."]) {
            [textView setText:@""];
            [textView setTextColor:C(@"585858")];
        }
    }else if (textView==_titleTF)
    {
        if ([textView.text isEqualToString:@"讨论贴标题"]) {
            [textView setText:@""];
            [textView setTextColor:C(@"585858")];
        }
    }
    
}
- (void)textViewDidChange:(UITextView *)textView{
   

    if(textView==_detailTF)
    {
     if (textView.markedTextRange == nil && textView.text.length > 200)  //加上 textView.markedTextRange == nil判断，当此属性为nil时，代表不在这种联想输入等待确定状态。
    {
            
        textView.text = [textView.text substringToIndex:200];
        
    }
    }else if (textView==_titleTF)
    {
        //移除表情
        if ([CClass stringContainsEmoji:textView.text]) {
            textView.text=[textView.text substringToIndex:textView.text.length-2];
            return;
        }

        if (textView.markedTextRange == nil && textView.text.length > 20)  //加上 textView.markedTextRange == nil判断，当此属性为nil时，代表不在这种联想输入等待确定状态。
            
        {
            
            textView.text = [textView.text substringToIndex:20];
            
        }
        
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (textView==_titleTF) {
        if ([[[UITextInputMode currentInputMode]primaryLanguage] isEqualToString:@"emoji"]) {
            return NO;
        }

    }
    return YES;
    
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
    
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 35;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _dataAr.count;
}
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    return [_dataAr objectAtIndex:row];
    
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
   self.type= [_dataAr objectAtIndex:row];
    
}
//打开系统相册
#pragma mark -- 打开系统相册
-(void)chooseClick
{
    UIActionSheet *sheet;
    
    //判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                   cancelButtonTitle:@"取消"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:@"拍照", @"从相册中选取", nil];
    }else
    {
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                   cancelButtonTitle:@"取消"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:@"从相册中选取", nil];
        
    }
    sheet.actionSheetStyle=UIActionSheetStyleBlackOpaque;
    sheet.tag = 200;
    [sheet showInView:self.view];
}


#pragma mark -- 判断是否支持相机 ，跳转到相机 或相册界面
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 200)
    {
        NSInteger sourceType = 0;
        //判断是否支持相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            switch (buttonIndex)
            {
                case 0:
                    //相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    
                    //取消
                    return;
                    break;
                default:
                    break;
            }
        }else
        {
            if (buttonIndex == 0)
            {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                
                ;
            }else if(buttonIndex==1)
            {
                return;
            }
        }
        
        //跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = sourceType;
        imagePickerController.allowsEditing = NO;
        //状态栏变成白色
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    [navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    navigationController.navigationBar.translucent = NO;
    [[UIApplication  sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [[UIApplication  sharedApplication]  setStatusBarHidden:NO];
    
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}
- (void)changeHeadImage{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.allowsEditing = YES;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    });
    
}
#pragma mark -- UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        picker.allowsEditing=YES;
        // _headImg.image = image;
        //设置image的尺寸
        //初始化imageNew为从相机中获得的--
        
        UIImage *imageNew = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *imageData=  [CClass compressImageQuality:imageNew];
        _imgView.image=[UIImage imageWithData:imageData];
        _newIamge=[UIImage imageWithData:imageData];
        isNewImg=YES;
        [_delView setHidden:NO];
        [self dismissViewControllerAnimated:YES completion:nil];
    });
}

-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}


@end
